package org.example.sword2offer.primary;

/**
 * @author: lynn
 * @Descript: 请实现两个函数，分别用来序列化和反序列化二叉树
 * @date: 2021/3/24 22:43
 *
 * https://blog.csdn.net/qq_36771269/article/details/79522511
 * @version: 1.0
 */
public class Q59_SerializeTreeNode {
    private static int  index=-1;
    public static void main(String[] args) {
        TreeNode treeNode =  new TreeNode(8);
        treeNode.left =      new TreeNode(4);
        treeNode.right =     new TreeNode(6);
        treeNode.left.left = new TreeNode(2);
        treeNode.left.right= new TreeNode(3);
        treeNode.right.left= new TreeNode(5);
        treeNode.right.right=new TreeNode(7);
        System.out.println(Serialize(treeNode));
        System.out.println(Deserialize(Serialize(treeNode)));
    }


    private static String Serialize(TreeNode root) {
        if(root == null){
            return "#,";
        }
        //处理头结点、左子树、右子树
        String res = root.val + ",";
        res += Serialize(root.left);
        res += Serialize(root.right);
        return res;   //先序遍历: 8_4_2_#_#_3_#_#_6_5_#_#_7_#_#_
    }

    private  static TreeNode Deserialize(String str) {
        if(str == null || str.length() == 0){
            return null;
        }
        String []s=str.split(",");//将序列化之后的序列用，分隔符转化为数组
        index++;//索引每次加一
        int len=s.length;
        if(index>len) {//鲁棒性
            return null;
        }
        TreeNode treeNode=null;
        if(!s[index].equals("#")) {//不是叶子节点 继续走 是叶子节点出递归
            treeNode=new TreeNode(Integer.parseInt(s[index]));
            treeNode.left=Deserialize(str);
            treeNode.right=Deserialize(str);
        }
        return treeNode;
    }






    private static class TreeNode{
        int val;
        TreeNode left;
        TreeNode right;
        public TreeNode(int val){
            this.val=val;
        }
    }
}
